import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Modal, Input, Button, List, Tree, Checkbox, message } from 'antd';
import { SearchOutlined, CloseOutlined, CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import '@/pages/components/selection-modal/ItemSelectionModal.css';

import datasetService from '@/api/services/datasetService'
export interface SelectionItem {
  id: string;
  name: string;
  children?: SelectionItem[];
}

export interface UserSelectModalProps {
  title: string;
  visible: boolean;
  dataSource: SelectionItem[];
  selectedIds?: string[];
  treeMode?: boolean;
  searchPlaceholder?: string;
  confirmText?: string;
  cancelText?: string;
  onCancel: () => void;
  onConfirm: (selectedItems: SelectionItem[]) => void;
}
interface page {
  page: number;
  page_size: number;
  group_id: any;
}

const UserSelectModal: React.FC<UserSelectModalProps> = ({
  title,
  visible,
  dataSource,
  selectedIds = [],
  treeMode = true,
  searchPlaceholder = "搜索",
  confirmText = "确定",
  cancelText = "取消",
  onCancel,
  onConfirm
}) => {
  // 选中的ID数组
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>(selectedIds);
  // 展开的节点ID数组（仅在树形模式下使用）
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  // 搜索值
  const [searchValue, setSearchValue] = useState('');
  // 保存过滤后可见的节点key
  const [visibleKeys, setVisibleKeys] = useState<Set<React.Key>>(new Set());
  const [getdata, setgetdata] = useState<page>({
    page: 1,
    page_size: 10,
    group_id: '',
  });
  const [userDatas, setUserDatas] = useState({
    list: [],
    total: 0,
  })

  const userAllRef = useRef(null)
  //下拉触底操作
  const Scroll = () => {
    if (userAllRef.current) {
      let height1 = userAllRef.current.clientHeight  // 可以得到我们设置的高度 (不包括滚动的高度)
      let height2 = userAllRef.current.scrollTop  // 当滚动时被卷去的高度
      let height3 = userAllRef.current.scrollHeight  // 全部的高度 包括滚动的高度
      if (height1 + height2 + 20 > height3) {   // 当距离底部20 则会触发
        console.log('触发了useAllRef');
        if (userDatas.total > userDatas.list.length) {

          //这里进行请求
          setgetdata(prev => ({
            page: prev.page + 1,
            page_size: 10,
            group_id: getdata.group_id,
          }));

        }
      }
    }
  }

  // 当传入的selectedIds改变时，更新内部状态
  useEffect(() => {
    setSelectedKeys(selectedIds);
  }, [selectedIds]);

  useEffect(() => {
    getUserGroup()
  }, [getdata.group_id, getdata.page])

  //获取选择的用户组数据
  const getUserGroup = async () => {
    //这个地方请求数据  暂时不接
    try {
      // const res = await datasetService.getGroupUser(getdata)

      // setUserDatas({
      //   list: [...userDatas.list, ...res.list],
      //   total: res.total,
      // })
    } catch (error) {
      message.error(error)
    }
  }

  // 获取某个节点下所有子节点的key
  const getAllChildrenKeys = (id: React.Key, items: SelectionItem[]): React.Key[] => {
    const result: React.Key[] = [];

    const findAndCollectKeys = (nodeId: React.Key, itemList: SelectionItem[]) => {
      for (const item of itemList) {
        if (item.id === nodeId) {
          if (item.children && item.children.length > 0) {
            item.children.forEach(child => {
              result.push(child.id);
              if (child.children && child.children.length > 0) {
                findAndCollectKeys(child.id, [child]);
              }
            });
          }
          return;
        }

        if (item.children && item.children.length > 0) {
          findAndCollectKeys(nodeId, item.children);
        }
      }
    };

    findAndCollectKeys(id, items);
    return result;
  };

  // 将数据转换为树节点格式
  const convertToTreeData = (items: SelectionItem[]): DataNode[] => {
    return items.map(item => ({
      key: item.id,
      title: item.name,
      children: item.children ? convertToTreeData(item.children) : undefined
    }));
  };

  // 将展平的ID列表转换回对象
  const getItemsFromKeys = (keys: React.Key[]): SelectionItem[] => {
    const result: SelectionItem[] = [];

    const findItemById = (id: React.Key, items: SelectionItem[]): SelectionItem | undefined => {
      for (const item of items) {
        if (item.id === id) {
          // 为对象添加完整路径信息以便显示
          const itemClone = { ...item };
          // 移除children防止右侧列表显示过于复杂
          delete itemClone.children;
          return itemClone;
        }
        if (item.children) {
          const found = findItemById(id, item.children);
          if (found) return found;
        }
      }
      return undefined;
    };

    keys.forEach(key => {
      const item = findItemById(key, dataSource);
      if (item) {
        result.push(item);
      }
    });

    return result;
  };

  // 处理搜索
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.trim();
    setSearchValue(value);

    if (value && treeMode) {
      // 搜索时展开所有匹配的节点
      const matchedKeys: React.Key[] = [];
      const searchNodes = (nodes: SelectionItem[]) => {
        nodes.forEach(node => {
          if (node.name.toLowerCase().includes(value.toLowerCase())) {
            matchedKeys.push(node.id);
          }
          if (node.children) {
            searchNodes(node.children);
          }
        });
      };
      searchNodes(dataSource);
      setExpandedKeys(matchedKeys);
    } else if (treeMode) {
      // 清空搜索时折叠所有节点
      setExpandedKeys([]);
    }
  };

  // 处理树形选择
  const handleTreeSelect = async (checkedKeys: React.Key[] | { checked: React.Key[]; halfChecked: React.Key[] }) => {
    // 当返回的checkedKeys是一个对象时，提取checked数组
    const keys = Array.isArray(checkedKeys) ? checkedKeys : checkedKeys.checked;

    // 处理子节点全选逻辑，但只处理可见的节点
    let allSelectedKeys = [...selectedKeys]; // 保留已选的节点

    // 移除被取消选中的节点
    allSelectedKeys = allSelectedKeys.filter(key =>
      keys.includes(key) || !visibleKeys.has(key)
    );


    // 添加新选中的节点
    keys.forEach(key => {
      if (!allSelectedKeys.includes(key)) {
        allSelectedKeys = [];// 选择之前都制空
        setUserDatas(prev => ({ list: prev.list = [], total: prev.total = 0 }))
        allSelectedKeys.push(key);
        setgetdata({ ...getdata, group_id: key, page: 1 })
      }
      //这个地方暂时注释掉
      // 只有当节点在可见范围内时，才获取其子节点
      // if (visibleKeys.has(key)) {
      //   const childrenKeys = getAllChildrenKeys(key, dataSource);
      //   // 只添加可见的子节点
      //   const visibleChildrenKeys = childrenKeys.filter(childKey => visibleKeys.has(childKey));

      //   // 合并子节点，避免重复
      //   visibleChildrenKeys.forEach(childKey => {
      //     if (!allSelectedKeys.includes(childKey)) {
      //       allSelectedKeys.push(childKey);
      //     }
      //   });
      // }
    });
    setSelectedKeys(allSelectedKeys);

  };

  // 处理列表选择
  const handleListSelect = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedKeys(prev => [...prev, id]);
    } else {
      setSelectedKeys(prev => prev.filter(key => key !== id));
    }
  };

  // 处理展开/折叠
  const handleExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
  };

  // 处理移除选中项
  const handleRemoveItem = (key: React.Key) => {
    setUserDatas({ ...userDatas, list: userDatas.list.filter(k => k.id !== key) });
    // setSelectedKeys(prev => prev.filter(key => key !== key));
  };

  // 确认选择
  const handleConfirm = () => {
    onConfirm(userDatas.list);
  };

  // 过滤树数据
  const filterTreeData = (data: DataNode[]): DataNode[] => {
    if (!searchValue) return data;

    // 保存匹配的节点key，用于后续选择
    const matchedNodeKeys: Set<React.Key> = new Set();

    const filterNodes = (nodes: DataNode[]): DataNode[] => {
      const result: DataNode[] = [];

      for (const node of nodes) {
        const nodeTitle = typeof node.title === 'string' ? node.title : '';
        const matchesSearch = nodeTitle.toLowerCase().includes(searchValue.toLowerCase());

        let filteredChildren: DataNode[] | undefined = undefined;
        if (node.children) {
          filteredChildren = filterNodes(node.children);
        }

        if (matchesSearch || (filteredChildren && filteredChildren.length > 0)) {
          // 将匹配的节点key加入到集合中
          matchedNodeKeys.add(node.key);
          // 如果子节点有匹配的，也加入它们的key
          if (filteredChildren && filteredChildren.length > 0) {
            filteredChildren.forEach(child => {
              matchedNodeKeys.add(child.key);
            });
          }

          result.push({
            ...node,
            children: filteredChildren,
          });
        }
      }

      return result;
    };

    const filteredResult = filterNodes(data);
    return filteredResult;
  };

  // 提取所有可见节点的key
  useEffect(() => {
    if (!searchValue) {
      // 如果没有搜索条件，所有节点都是可见的
      const allKeys = new Set<React.Key>();
      const extractAllKeys = (items: SelectionItem[]) => {
        items.forEach(item => {
          allKeys.add(item.id);
          if (item.children) {
            extractAllKeys(item.children);
          }
        });
      };
      extractAllKeys(dataSource);
      setVisibleKeys(allKeys);
    } else {
      const visibleNodeKeys = new Set<React.Key>();

      const extractKeys = (nodes: DataNode[]) => {
        nodes.forEach(node => {
          visibleNodeKeys.add(node.key);
          if (node.children) {
            extractKeys(node.children);
          }
        });
      };

      extractKeys(treeData);
      setVisibleKeys(visibleNodeKeys);
    }
  }, [searchValue, dataSource]);

  // 树的渲染配置
  const treeData = filterTreeData(convertToTreeData(dataSource));


  // 过滤列表数据
  const filteredListItems = !treeMode && searchValue
    ? dataSource.filter(item => item.name.toLowerCase().includes(searchValue.toLowerCase()))
    : dataSource;

  return (
    <Modal
      title={title}
      open={visible}
      footer={null}
      onCancel={onCancel}
      width={640}
      styles={{ body: { padding: '5px' } }}
      maskClosable={false}
      centered
    >
      <div className="flex h-[300px] border border-[#C9CEE2] rounded-lg p-4">
        {/* 左侧搜索与列表 */}
        <div className="w-1/2 border-r border-[#C9CEE2] pr-4">
          <Input
            placeholder={searchPlaceholder}
            prefix={<SearchOutlined style={{ color: '#C0C6CC' }} />}
            className="mb-4"
            value={searchValue}
            onChange={handleSearchChange}
          />
          <div className="overflow-auto h-[220px]">
            {treeMode ? (
              <Tree
                checkable
                checkedKeys={selectedKeys}
                expandedKeys={expandedKeys}
                onCheck={handleTreeSelect}
                onExpand={handleExpand}
                treeData={treeData}
                switcherIcon={({ expanded }) => expanded ?
                  <CaretDownOutlined className="text-[#C0C6CC]" /> :
                  <CaretRightOutlined className="text-[#C0C6CC]" />}
                blockNode
                checkStrictly
              />
            ) : (
              <List
                dataSource={filteredListItems}
                renderItem={item => (
                  <List.Item className="p-2 hover:bg-[#F5F7FA]">
                    <Checkbox
                      checked={selectedKeys.includes(item.id)}
                      onChange={(e) => handleListSelect(item.id, e.target.checked)}
                    >
                      <span className="text-[#4E5969]">{item.name}</span>
                    </Checkbox>
                  </List.Item>
                )}
              />
            )}
          </div>
        </div>

        {/* 右侧已选项 */}
        <div className="w-1/2 pl-4">
          <div className="mb-4 text-[#86909C]">已选: {userDatas.list.length} 个</div>
          <div className="overflow-auto h-[220px]" ref={userAllRef} onScroll={Scroll} >
            <List
              dataSource={userDatas.list}
              renderItem={item => (
                <List.Item className="p-2 hover:bg-[#F5F7FA]">
                  <div className="flex justify-between w-full items-center">
                    <span>{item.name}</span>
                    <CloseOutlined
                      className="text-[#C0C6CC] cursor-pointer"
                      onClick={() => handleRemoveItem(item.id)}
                    />
                  </div>
                </List.Item>
              )}
            />
          </div>
        </div>
      </div>

      {/* 底部按钮 */}
      <div className="flex justify-end mt-4">
        <Button
          className="mr-2 bg-[#F7F8FA] border-[#E5E6EB] text-[#4E5969]"
          onClick={onCancel}
        >
          {cancelText}
        </Button>
        <Button
          type="primary"
          className="bg-[#6857D6]"
          onClick={handleConfirm}
          disabled={userDatas.list.length === 0}
        >
          {confirmText}{userDatas.list.length > 0 ? ` (${userDatas.list.length})` : ''}
        </Button>
      </div>
    </Modal>
  );
};

export default UserSelectModal; 